package com.ls.bigdata.config;

import com.ls.bigdata.filter.CaptchaFilter;
import com.ls.bigdata.handler.AuthenticationEntryPointImpl;
import com.ls.bigdata.handler.AuthenticationFailHandlerImpl;
import com.ls.bigdata.handler.AuthenticationSuccessHandlerIml;
import com.ls.bigdata.handler.LogoutSuccessHandlerIml;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @program: bit-data
 * @author: lishun
 * @create: 2021-09-24 13:01
 **/
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthenticationSuccessHandlerIml authenticationSuccessHandler;
    @Autowired
    private AuthenticationFailHandlerImpl authenticationFailureHandler;
    @Autowired
    private AuthenticationEntryPointImpl authenticationEntryPoint;
    @Autowired
    private LogoutSuccessHandlerIml logoutSuccessHandlerIml;
    @Autowired
    CaptchaFilter captchaFilter;
    private static final String[] URL_WHITELIST = {
            "/login",
            "/logout",
            "/captcha",
            "/favicon.ico",
    };

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers(URL_WHITELIST).permitAll()
                .anyRequest().authenticated();
        // 关闭跨域拦截伪造
         http.csrf().disable().exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);
        // 认证成功失败处理
        http.logout().logoutSuccessHandler(logoutSuccessHandlerIml);
        http.formLogin().
                loginProcessingUrl("/login")
                .successHandler(authenticationSuccessHandler)
                .failureHandler(authenticationFailureHandler);
        http.addFilterBefore(captchaFilter, UsernamePasswordAuthenticationFilter.class);
    }

}
